import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';
import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'package:kudos/core/utils/kudo_colors.dart';
import '../../utils/video_resource_helper.dart';

class KiteVideoPlayerScreen extends StatefulWidget {
  final String videoResourceUrl;

  const KiteVideoPlayerScreen({super.key, required this.videoResourceUrl});

  @override
  State<KiteVideoPlayerScreen> createState() => _KiteVideoPlayerScreenState();
}

class _KiteVideoPlayerScreenState extends State<KiteVideoPlayerScreen> {
  VideoPlayerController? _videoController;
  final ReactiveValueNotifier<bool> _isPlayingState =
      ReactiveValueNotifier<bool>(false);
  final ReactiveValueNotifier<bool> _showControlsState =
      ReactiveValueNotifier<bool>(true);
  final ReactiveValueNotifier<Duration> _positionState =
      ReactiveValueNotifier<Duration>(Duration.zero);
  final ReactiveValueNotifier<Duration> _durationState =
      ReactiveValueNotifier<Duration>(Duration.zero);

  @override
  void initState() {
    super.initState();
    _initializeVideoPlayer();
    _setupControlsAutoHide();
  }

  @override
  void dispose() {
    _videoController?.dispose();
    _isPlayingState.dispose();
    _showControlsState.dispose();
    _positionState.dispose();
    _durationState.dispose();
    super.dispose();
  }

  void _initializeVideoPlayer() async {
    try {
      _videoController = await VideoResourceHelper.createVideoController(
        widget.videoResourceUrl,
      );

      if (_videoController != null) {
        await _videoController!.initialize();

        _videoController!.addListener(_videoPlayerListener);

        _durationState.value = _videoController!.value.duration;

        _videoController!.play();
        _isPlayingState.value = true;

        setState(() {});
      }
    } catch (e) {
      debugPrint('视频加载失败: $e');
    }
  }

  void _videoPlayerListener() {
    if (_videoController != null) {
      _positionState.value = _videoController!.value.position;
      _isPlayingState.value = _videoController!.value.isPlaying;
    }
  }

  void _setupControlsAutoHide() {
    Future.delayed(const Duration(seconds: 3), () {
      if (mounted) {
        _showControlsState.value = false;
      }
    });
  }

  void _toggleControlsVisibility() {
    _showControlsState.value = !_showControlsState.value;

    if (_showControlsState.value) {
      Future.delayed(const Duration(seconds: 3), () {
        if (mounted && _showControlsState.value) {
          _showControlsState.value = false;
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);

    return Scaffold(
      backgroundColor: Colors.black,
      body:
          _videoController?.value.isInitialized == true
              ? _buildVideoPlayerContent()
              : _buildLoadingState(),
    );
  }

  Widget _buildVideoPlayerContent() {
    return Stack(
      children: [
        _buildVideoBackground(),
        _buildTapArea(),
        _buildControlsOverlay(),
      ],
    );
  }

  Widget _buildVideoBackground() {
    return SizedBox.expand(
      child: FittedBox(
        fit: BoxFit.cover,
        child: SizedBox(
          width: _videoController!.value.size.width,
          height: _videoController!.value.size.height,
          child: VideoPlayer(_videoController!),
        ),
      ),
    );
  }

  Widget _buildTapArea() {
    return GestureDetector(
      onTap: _toggleControlsVisibility,
      child: Container(
        width: double.infinity,
        height: double.infinity,
        color: Colors.transparent,
      ),
    );
  }

  Widget _buildControlsOverlay() {
    return _showControlsState.reactiveValue(context)
        ? [
          _buildTopControls(),
          const Spacer(),
          _buildBottomControls(),
        ].toColumn()
        : const SizedBox.shrink();
  }

  Widget _buildTopControls() {
    return Container(
      padding: EdgeInsets.only(
        top: MediaQuery.of(context).padding.top + 16.h,
        left: 16.w,
        right: 16.w,
      ),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Colors.black.withValues(alpha: 0.7), Colors.transparent],
        ),
      ),
      child:
          [
            Container(
              width: 40.w,
              height: 40.h,
              decoration: BoxDecoration(
                color: Colors.black.withValues(alpha: 0.5),
                shape: BoxShape.circle,
              ),
              child:
                  Icon(
                    Icons.arrow_back_ios_new,
                    color: Colors.white,
                    size: 20.sp,
                  ).center(),
            ).inkWell(onTap: _handleBackButtonTap),
            const Spacer(),
          ].toRow(),
    );
  }

  Widget _buildBottomControls() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [Colors.transparent, Colors.black.withValues(alpha: 0.7)],
        ),
      ),
      child:
          [
            Container(
              width: 40.w,
              height: 40.h,
              decoration: BoxDecoration(
                color: Colors.black.withValues(alpha: 0.5),
                shape: BoxShape.circle,
              ),
              child:
                  Icon(
                    _isPlayingState.reactiveValue(context)
                        ? Icons.pause
                        : Icons.play_arrow,
                    color: Colors.white,
                    size: 24.sp,
                  ).center(),
            ).inkWell(onTap: _togglePlayPause),

            SizedBox(width: 8.w),

            _buildProgressBar().expanded(),

            SizedBox(width: 8.w),

            Text(
              _formatDuration(_positionState.reactiveValue(context)),
            ).fontSize(12.sp).textColor(Colors.white),
            Text(' / ').fontSize(12.sp).textColor(Colors.white),
            Text(
              _formatDuration(_durationState.reactiveValue(context)),
            ).fontSize(12.sp).textColor(Colors.white),
          ].toRow(),
    );
  }

  Widget _buildProgressBar() {
    final position = _positionState.reactiveValue(context);
    final duration = _durationState.reactiveValue(context);
    final progress =
        duration.inMilliseconds > 0
            ? position.inMilliseconds / duration.inMilliseconds
            : 0.0;

    return SliderTheme(
      data: SliderTheme.of(context).copyWith(
        activeTrackColor: KudoColors.green,
        inactiveTrackColor: Colors.white.withValues(alpha: 0.3),
        thumbColor: KudoColors.green,
        thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 6),
        trackHeight: 3,
      ),
      child: Slider(
        value: progress.clamp(0.0, 1.0),
        onChanged: _onProgressChanged,
      ),
    );
  }

  Widget _buildLoadingState() {
    return [
      CircularProgressIndicator(color: KudoColors.green).center(),
      SizedBox(height: 16.h),
      Text('Loading Video...').fontSize(16.sp).textColor(Colors.white).center(),
    ].toColumn(mainAxisAlignment: MainAxisAlignment.center);
  }

  void _handleBackButtonTap() {
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
    Navigator.of(context).pop();
  }

  void _togglePlayPause() {
    if (_videoController != null) {
      if (_videoController!.value.isPlaying) {
        _videoController!.pause();
      } else {
        _videoController!.play();
      }
    }
  }

  void _onProgressChanged(double value) {
    if (_videoController != null) {
      final duration = _videoController!.value.duration;
      final newPosition = Duration(
        milliseconds: (duration.inMilliseconds * value).round(),
      );
      _videoController!.seekTo(newPosition);
    }
  }

  String _formatDuration(Duration duration) {
    final minutes = duration.inMinutes.toString().padLeft(2, '0');
    final seconds = (duration.inSeconds % 60).toString().padLeft(2, '0');
    return '$minutes:$seconds';
  }
}
